﻿using Admin.CommonLib.Models.User;
using Admin.RazorLib.Services;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Newtonsoft.Json;
using Radzen;
using Swimj.CommonLib.Base;
using System.Diagnostics.CodeAnalysis;

namespace Admin.RazorLib.Pages;

public partial class UserEdit
{
    private UserEditRequestDto _editRequestDto = new();

    [Parameter] public Guid? Key { get; set; }

    [Inject]
    [NotNull]
    public DialogService DialogService { get; set; }

    [Inject]
    [NotNull]
    public IUserService UserService { get; set; }

    private void CompleteUploadHandler(UploadCompleteEventArgs args)
    {
        if (!string.IsNullOrEmpty(args.RawResponse))
        {
            var result = JsonConvert.DeserializeObject<Result<string>>(args.RawResponse);
            _editRequestDto.Avatar = result.Data;
        }
    }

    private void ProgressUploadHandler(UploadProgressArgs args)
    {
        if (args.Progress == 100)
        {
            foreach (var file in args.Files)
            {

            }
        }
    }

    async Task OnSubmit()
    {
        if (Key != null)
        {
            var result = await UserService.UpdateUser(Key.Value, _editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
        else
        {
            var result = await UserService.CreateUser(_editRequestDto);

            if (result.Succeeded)
            {
                DialogService.Close(null);
            }
        }
    }

    protected void CancelButtonClick(MouseEventArgs args)
    {
        DialogService.Close(null);
    }

    protected override async Task OnParametersSetAsync()
    {
        _editRequestDto = new UserEditRequestDto();
        if (Key.HasValue)
        {
            var result = await UserService.GetUser(Key.Value);
            if (result.Succeeded && result.Data != null)
            {
                _editRequestDto.UserName = result.Data.UserName;
                _editRequestDto.RealName = result.Data.RealName;
                _editRequestDto.Email = result.Data.Email;
                _editRequestDto.Phone = result.Data.Phone;
                _editRequestDto.DataState = (UserStateEnum)result.Data.DataState;
                _editRequestDto.Sex = result.Data.Sex;
                _editRequestDto.Birthday = result.Data.Birthday;
                _editRequestDto.Avatar = result.Data.Avatar;
                _editRequestDto.Description = result.Data.Description;
            }
        }
    }

}